package jiguang.ui.fragment.conversation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.app.JGApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.ui.activity.main.MainActivity;
import com.jiuyin.dianjing.ui.fragment.main.FragmentFour;
import com.jiuyin.dianjing.util.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.event.ConversationRefreshEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.MessageReceiptStatusChangeEvent;
import cn.jpush.im.android.api.event.MessageRetractEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import jiguang.controller.ConversationListController;
import jiguang.controller.MenuItemController;
import jiguang.entity.Event;
import jiguang.ui.fragment.base.BaseFragment;
import jiguang.ui.view.ConversationListView;
import jiguang.ui.view.MenuItemView;
import jiguang.util.SharePreferenceManager;

import static com.jiuyin.dianjing.constant.AppConstant.JG_SYSTEM_TARGET_ID;
import static com.jiuyin.dianjing.ui.fragment.main.FragmentFour.USER_NAME;

/**
 * 会话列表
 */

public class ConversationListFragment extends BaseFragment {
    @BindView(R.id.ll_system_notice)
    LinearLayout mSystemLinearLayout;

    @BindView(R.id.iv_header)
    ImageView mSystemHeader;

    @BindView(R.id.tv_system_title)
    TextView mSystemTitle;

    @BindView(R.id.tv_system_notice)
    TextView mSystemNotice;

    @BindView(R.id.tv_system_notice_time)
    TextView mSystemTime;

    private View mRootView;
    private ConversationListView mConvListView;
    private ConversationListController mConvListController;
    private HandlerThread mThread;
    private static final int REFRESH_CONVERSATION_LIST = 0x3000;
    private static final int DISMISS_REFRESH_HEADER = 0x3001;
    private static final int ROAM_COMPLETED = 0x3002;
    private BackgroundHandler mBackgroundHandler;
    private View mMenuView;
    private MenuItemView mMenuItemView;

    private PopupWindow mMenuPopWindow;
    private NetworkReceiver mReceiver;
    private MenuItemController mMenuController;
    protected boolean isCreate = false;
    private Unbinder mUnBinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        isCreate = true;
        mActivity = this.getActivity();
        initReceiver();
    }

    private void initReceiver() {
        mReceiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        mActivity.registerReceiver(mReceiver, filter);
    }

    @OnClick(R.id.ll_system_notice)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        bundle.putString(USER_NAME, JG_SYSTEM_TARGET_ID);
        startContainerActivity(FragmentFour.class.getCanonicalName(), bundle);
    }

    //监听网络状态的广播
    private class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
                ConnectivityManager manager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeInfo = manager.getActiveNetworkInfo();
                if (null == activeInfo) {
                    mConvListView.showHeaderView();
                } else {
                    mConvListView.dismissHeaderView();
                }
            }
        }
    }

    public void showPopWindow() {
        mMenuPopWindow.setTouchable(true);
        mMenuPopWindow.setOutsideTouchable(true);
        mMenuPopWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        if (mMenuPopWindow.isShowing()) {
            mMenuPopWindow.dismiss();
        } else {
            mMenuPopWindow.showAsDropDown(mRootView.findViewById(R.id.create_group_btn), -10, -5);
        }
    }

    /**
     * 收到消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        SharePreferenceManager.setUnReadMsgNum(SharePreferenceManager.getUnReadMsgNum() + 1);
        EventBus.getDefault().post(new RefreshEvent(MainActivity.class.getSimpleName()));
        Message msg = event.getMessage();
        boolean ret = hasSystemMsg(msg);
        LogUtil.log("onEvent ret = " + ret + ",msg = " + msg.toJson());
        if (ret) {
            String content = msg.getContent().toJson();
            HelperApplication.setJgLastSystemMsg(content);
            updateSystemMsg(content);
        } else {
            if (msg.getTargetType() == ConversationType.group) {
                long groupId = ((GroupInfo) msg.getTargetInfo()).getGroupID();
                Conversation conv = JMessageClient.getGroupConversation(groupId);
                if (conv != null && mConvListController != null) {
                    if (msg.isAtMe()) {
                        JGApplication.isAtMe.put(groupId, true);
                        mConvListController.getAdapter().putAtConv(conv, msg.getId());
                    }
                    if (msg.isAtAll()) {
                        JGApplication.isAtall.put(groupId, true);
                        mConvListController.getAdapter().putAtAllConv(conv, msg.getId());
                    }
                    mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST,
                            conv));
                }
            } else {
                final UserInfo userInfo = (UserInfo) msg.getTargetInfo();
                String targetId = userInfo.getUserName();
                Conversation conv = JMessageClient.getSingleConversation(targetId, userInfo.getAppKey());
                if (conv != null && mConvListController != null) {
                    mActivity.runOnUiThread(() -> {
                        if (TextUtils.isEmpty(userInfo.getAvatar())) {
                            userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                @Override
                                public void gotResult(int responseCode, String responseMessage, Bitmap avatarBitmap) {
                                    if (responseCode == 0) {
                                        mConvListController.getAdapter().notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    });
                    mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
                }
            }
        }
    }

    /**
     * 接收离线消息
     *
     * @param event 离线消息事件
     */
    public void onEvent(OfflineMessageEvent event) {
        List<Message> offlineMsgList = event.getOfflineMessageList();
        for (Message message : offlineMsgList) {
            String content = message.toJson();
            LogUtil.log("OfflineMessageEvent onEvent content = " + content);
        }
        Conversation conv = event.getConversation();
        if (!conv.getTargetId().equals("feedback_Android") && conv.getType() != ConversationType.chatroom) {
            mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
        }
    }

    /**
     * 消息撤回
     */
    public void onEvent(MessageRetractEvent event) {
        boolean ret = hasSystemMsg(event.getRetractedMessage());
        Conversation conversation = event.getConversation();
        if (!ret) {
            mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conversation));
        }
    }

    /**
     * 消息已读事件
     */
    public void onEventMainThread(MessageReceiptStatusChangeEvent event) {
        LogUtil.log("MessageReceiptStatusChangeEvent onEvent event = " + event.getConversation().toJson());
        mConvListController.getAdapter().notifyDataSetChanged();
    }

    /**
     * 消息漫游完成事件
     */
    public void onEvent(ConversationRefreshEvent event) {
        LogUtil.log("onEvent3");
        Conversation conv = event.getConversation();
        if (!conv.getTargetId().equals("feedback_Android") && conv.getType() != ConversationType.chatroom) {
            mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
            //多端在线未读数改变时刷新
            if (event.getReason().equals(ConversationRefreshEvent.Reason.UNREAD_CNT_UPDATED)) {
                mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
            }
        }
    }

    private class BackgroundHandler extends Handler {
        public BackgroundHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_CONVERSATION_LIST:
                    Conversation conv = (Conversation) msg.obj;
                    if (conv.getType() != ConversationType.chatroom) {
                        mConvListController.getAdapter().setToTop(conv);
                    }
                    break;
                case DISMISS_REFRESH_HEADER:
                    mActivity.runOnUiThread(() -> mConvListView.dismissLoadingHeader());
                    break;
                case ROAM_COMPLETED:
                    conv = (Conversation) msg.obj;
                    mConvListController.getAdapter().addAndSort(conv);
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        LogUtil.log("event onEvent event = " + event.getConversation().toJson());
        switch (event.getType()) {
            case createConversation:
                Conversation conv = event.getConversation();
                if (conv != null) {
                    mConvListController.getAdapter().addNewConversation(conv);
                }
                break;
            case deleteConversation:
                conv = event.getConversation();
                if (null != conv) {
                    mConvListController.getAdapter().deleteConversation(conv);
                }
                break;
            //收到保存为草稿事件
            case draft:
                conv = event.getConversation();
                String draft = event.getDraft();
                //如果草稿内容不为空，保存，并且置顶该会话
                if (!TextUtils.isEmpty(draft)) {
                    mConvListController.getAdapter().putDraftToMap(conv, draft);
                    mConvListController.getAdapter().setToTop(conv);
                    //否则删除
                } else {
                    mConvListController.getAdapter().delDraftFromMap(conv);
                }
                break;
            case addFriend:
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_conv_list, container, false);
        mConvListView = new ConversationListView(mRootView, this.getActivity(), this);
        mConvListView.initModule();
        mThread = new HandlerThread("MainActivity");
        mThread.start();
        mBackgroundHandler = new BackgroundHandler(mThread.getLooper());
        mMenuView = getActivity().getLayoutInflater().inflate(R.layout.drop_down_menu, null);
        mMenuItemView = new MenuItemView(mMenuView);
        mMenuItemView.initModule();
        mMenuController = new MenuItemController(this);
        mMenuItemView.setListeners(mMenuController);
        mConvListController = new ConversationListController(mConvListView, this, mWidth);
        mConvListView.setListener(mConvListController);
        mConvListView.setItemListeners(mConvListController);
        mConvListView.setLongClickListener(mConvListController);
        mMenuPopWindow = new PopupWindow(mMenuView, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, true);
        ConnectivityManager manager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = manager.getActiveNetworkInfo();
        if (null == activeInfo) {
            mConvListView.showHeaderView();
        } else {
            mConvListView.dismissHeaderView();
            mConvListView.showLoadingHeader();
            mBackgroundHandler.sendEmptyMessageDelayed(DISMISS_REFRESH_HEADER, 1000);
        }
        mUnBinder = ButterKnife.bind(this, mRootView);
        return mRootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        dismissPopWindow();
        String content = HelperApplication.getJgLastSystemMsg();
        if (!TextUtils.isEmpty(content)) {
            updateSystemMsg(content);
        } else {
            mSystemLinearLayout.setEnabled(false);
        }
        mMenuItemView.showAddFriend();
        if (JGApplication.delConversation != null) {
            mConvListController.delConversation();
        }
        mConvListController.getAdapter().notifyDataSetChanged();
    }

    public void dismissPopWindow() {
        if (mMenuPopWindow.isShowing()) {
            mMenuPopWindow.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        mUnBinder.unbind();
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mActivity.unregisterReceiver(mReceiver);
        mBackgroundHandler.removeCallbacksAndMessages(null);
        mThread.getLooper().quit();
        super.onDestroy();
    }

    private void updateSystemMsg(String msg) {
        try {
            JSONObject jsonObject = new JSONObject(msg);
            String text = jsonObject.getString("text");
            JSONObject textJson = new JSONObject(text);
            String time = textJson.getString("time");
            String title = textJson.getString("title");
            String content = textJson.getString("content");
            mSystemNotice.setText(content);
            mSystemTime.setText(time);
            mSystemTitle.setText(title);
        } catch (JSONException e) {
            LogUtil.log("reason " + e.getMessage());
        }
        mSystemLinearLayout.setEnabled(true);
    }

    /**
     * 是否含有系统消息 含有系统消息（true）
     *
     * @param msg
     * @return
     */
    private boolean hasSystemMsg(Message msg) {
        Map<String, String> map = msg.getContent().getStringExtras();
        return (map.size() != 0);
    }
}
